from rest_framework.authentication import SessionAuthentication
from apps.user_operation.APIauthentication import APIJSONWebTokenAuthentication
from rest_framework import mixins, viewsets, status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from .APISerializers import *
from core.tools.custom_views import get_exception
from apps.user_operation.APIClient import api_client
from django.shortcuts import HttpResponse
from rest_framework.views import APIView
from apps.user_operation.permissions import BuyGasOwner
from .client import get_czb_api


# 初始化加油站列表(车主邦数据无更新)
class InitGasViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = BaseSerializers

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            data = InitGasSerializers(GasStationInfo.objects.prefetch_related("oilinfo_set").all(), many=True).data
            content = {"result": data, "message": "OK", "code": 200}
            return Response(content, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 用户获取加油站列表（车主邦数据无更新）
class QueryGasByPhoneViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    serializer_class = ApiQueryGasByPhoneSerializers
    authentication_classes = (APIJSONWebTokenAuthentication, SessionAuthentication)

    # authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        response = self.perform_create(serializer)
        return Response(response, status=status.HTTP_200_OK)

    def perform_create(self, serializer):
        return serializer.save()


# 提交订单接口
class GenerateOrdersViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = ApiOrdersSerializers
    permission_classes = (IsAuthenticated,)
    authentication_classes = (APIJSONWebTokenAuthentication, SessionAuthentication)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        response = self.perform_create(serializer)
        return Response(response, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()


# 查询订单接口
class QueryOrdersViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = QueryOrdersSerializers

    @get_exception()
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        response = self.perform_create(serializer)
        return Response(response, status=status.HTTP_200_OK, headers=response)

    def perform_create(self, serializer):
        return serializer.save()


# 购买权益
# class EquityViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
#     """
#     create: 订单创建
#     list: 订单查询
#     update:订单取消
#     """
#     authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
#     permission_classes = (IsAuthenticated,)
#     serializer_class = EquityCancelSerializers
#
#     def initial(self, request, *args, **kwargs):
#         super(EquityViewSet, self).initial(request, *args, **kwargs)
#         user = self.request.user
#         if hasattr(user, "userprofileextend"):
#             if user.userprofileextend.czb_auth:
#                 pass
#             else:
#                 token = czb_api.get_token_from_mc(user.mobile)
#                 if token:
#                     user.userprofileextend.czb_auth = True
#                     user.userprofileextend.save()
#                 else:
#                     content = {"errmsg": "注册失败，请刷新重试"}
#                     return Response(content, status=status.HTTP_400_BAD_REQUEST)
#         else:
#             token = czb_api.get_token_from_mc(user.mobile)
#             if token:
#                 UserProfileExtend.objects.create(user=user, czb_auth=True)
#             else:
#                 content = {"errmsg": "注册失败，请刷新重试"}
#                 return Response(content, status=status.HTTP_400_BAD_REQUEST)


# 取消订单
class CancelOrdersViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = OrdersCancelSerializers
    permission_classes = (IsAuthenticated,)
    authentication_classes = (APIJSONWebTokenAuthentication, SessionAuthentication)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        response = self.perform_create(serializer)
        return Response(response, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()


# 支付回告接口
class PayCallbackViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = PayCallbackSerializers
    permission_classes = (IsAuthenticated,)
    authentication_classes = (APIJSONWebTokenAuthentication, SessionAuthentication)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        response = self.perform_create(serializer)
        return Response(response, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()


# 申请退款
class RefundViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = RefundSerializers
    permission_classes = (IsAuthenticated,)
    authentication_classes = (APIJSONWebTokenAuthentication, SessionAuthentication)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        response = self.perform_create(serializer)
        return Response(response, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()


# 购买权益
class EquityViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = EquitySerializers
    permission_classes = (IsAuthenticated,)
    authentication_classes = (APIJSONWebTokenAuthentication, SessionAuthentication)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        order = self.perform_create(serializer)
        data = {"outerOrderId": order.outerOrderId}
        content = {"result": data, "message": "OK", "code": 200}
        return Response(content, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.save()


# 查询直降金额
class DepreciateAmountViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = DepreciateAmountSerializers
    permission_classes = (IsAuthenticated,)
    authentication_classes = (APIJSONWebTokenAuthentication, SessionAuthentication)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        response = self.perform_create(serializer)
        return Response(response, status=status.HTTP_200_OK)

    def perform_create(self, serializer):
        return serializer.save()


# 发票查询
class QueryInvoice(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = QueryInvoiceSerializers
    permission_classes = (IsAuthenticated,)
    authentication_classes = (APIJSONWebTokenAuthentication, SessionAuthentication)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        response = self.perform_create(serializer)
        return Response(response, status=status.HTTP_200_OK)

    def perform_create(self, serializer):
        return serializer.save()


# 开发票接口
class Invoice(mixins.CreateModelMixin, viewsets.GenericViewSet):
    serializer_class = OrderTicketSerializers
    permission_classes = (IsAuthenticated,)
    authentication_classes = (APIJSONWebTokenAuthentication, SessionAuthentication)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        response = self.perform_create(serializer)
        return Response(response, status=status.HTTP_200_OK)

    def perform_create(self, serializer):
        return serializer.save()


# 测试退款回调通知
class CallBackTest(APIView):
    def post(self, request):
        a = request.data
        sign = a.pop("sign")
        v_sign = api_client.get_sign(a, "008b58b1b35601230b216e6bbc18448b")
        print(sign)
        print(v_sign)
        return HttpResponse("SUCCESS")

    def get(self, request):
        return HttpResponse("SUCCESS")
